package org.edu.modules.kwgl.controller;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang.StringUtils;
import org.edu.common.system.base.controller.BaseController;
import org.edu.common.api.vo.Result;
import org.edu.common.system.query.QueryGenerator;
import org.edu.common.util.oConvertUtils;
import org.edu.modules.kwgl.api.CommonApi;
import org.edu.modules.kwgl.config.ConfigConstant;
import org.edu.modules.kwgl.entity.VeJwCjFree;
import org.edu.modules.kwgl.entity.VeJwCjFreeXs;
import org.edu.modules.kwgl.entity.VeJwCjlx;
import org.edu.modules.kwgl.service.IVeJwCjFreeService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.edu.modules.kwgl.service.IVeJwCjFreeXsService;
import org.edu.modules.kwgl.utils.JwTextUtils;
import org.edu.modules.scheduleCommon.entity.VeBaseBanji;
import org.edu.modules.scheduleCommon.entity.VeBaseStudent;
import org.edu.modules.scheduleCommon.service.VeBaseBanjiService;
import org.edu.modules.scheduleCommon.service.VeBaseStudentService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.edu.common.aspect.annotation.AutoLog;

/**
 * @Description: 免缓缺成绩登记
 * @Author: jeecg-boot
 * @Date: 2021-05-12
 * @Version: V1.0
 */
@Api(tags = "免缓缺成绩登记")
@RestController
@RequestMapping("/kwgl/veJwCjFree")
@Slf4j
public class VeJwCjFreeController extends BaseController<VeJwCjFree, IVeJwCjFreeService> {
    @Autowired
    private IVeJwCjFreeService veJwCjFreeService;

    @Autowired
    private IVeJwCjFreeXsService veJwCjFreeXsService;

    @Autowired
    private CommonApi commonApi;

    @Autowired
    private VeBaseStudentService veBaseStudentService;

    @Autowired
    private VeBaseBanjiService veBaseBanjiService;

    /**
     * 分页列表查询
     *
     * @param veJwCjFree
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "免缓缺成绩登记-分页列表查询")
    @ApiOperation(value = "免缓缺成绩登记-分页列表查询", notes = "免缓缺成绩登记-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(VeJwCjFree veJwCjFree,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<VeJwCjFree> queryWrapper = QueryGenerator.initQueryWrapper(veJwCjFree, req.getParameterMap());
        Page<VeJwCjFree> page = new Page<VeJwCjFree>(pageNo, pageSize);
        IPage<VeJwCjFree> pageList = veJwCjFreeService.page(page, queryWrapper);
        VeJwCjFreeXs freexs = null;
        for (VeJwCjFree item : pageList.getRecords()) {
            freexs = veJwCjFreeXsService.getByFreeid(item.getId());
            if (freexs != null) {
                item.setFreeXs(freexs);
            }
            item.setAudittidText(JwTextUtils.getText(item.getAudittid()));
            item.setReasontidText(JwTextUtils.getText(item.getReasontid()));
        }
        return Result.ok(pageList);
    }

    /**
     * 添加
     *
     * @param veJwCjFree
     * @return
     */
    @AutoLog(value = "免缓缺成绩登记-添加")
    @ApiOperation(value = "免缓缺成绩登记-添加", notes = "免缓缺成绩登记-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody VeJwCjFree veJwCjFree) {
        VeJwCjFreeXs fx = veJwCjFree.getFreeXs();
        if (fx != null) {
            if (fx.getRatio().compareTo(new BigDecimal("100.0")) > 0) {
                return Result.error("占总成绩的百分比不能超过100%！");
            }
            fx.setFinalscore(new BigDecimal(0));
            veJwCjFreeXsService.save(fx);
        }
		/*try {
			Result<JSONObject> result = commonApi.getStudentById(CommonApi.COMMON_TOKEN_KEY,veJwCjFree.getStuid());
			JSONObject student = result.getResult();
			if(student==null){
				return Result.error("学生信息错误！");
			}
			veJwCjFree.setXm(student.getString("xm"));
			veJwCjFree.setXh(student.getString("xh"));
		}catch (Exception e){
			return Result.error("学生信息错误%！");
		}*/

        VeBaseStudent student = veBaseStudentService.getById(veJwCjFree.getStuid());
        if (student != null) {
            veJwCjFree.setXm(student.getXm());
            veJwCjFree.setXh(student.getXh());
        }
        //根据班级id找班级信息
        VeBaseBanji veBaseBanji = veBaseBanjiService.findById(veJwCjFree.getJxbid());
        if (veBaseBanji != null) {
            veJwCjFree.setGradeid(veBaseBanji.getGradeId());
        }
        if (veJwCjFree.getReasontidText() != null) {
            veJwCjFree.setReasontid(JwTextUtils.addText(veJwCjFree.getReasontidText()));
        }
        veJwCjFreeService.save(veJwCjFree);
        return Result.ok("添加成功！");
    }

    /**
     * 编辑
     *
     * @param veJwCjFree
     * @return
     */
    @AutoLog(value = "免缓缺成绩登记-编辑")
    @ApiOperation(value = "免缓缺成绩登记-编辑", notes = "免缓缺成绩登记-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody VeJwCjFree veJwCjFree) {
        VeJwCjFreeXs fx = veJwCjFree.getFreeXs();
        if (fx != null) {
            //todo 对freexs信息的判断
            if (fx.getRatio().compareTo(new BigDecimal("100.0")) > 0) {
                return Result.error("占总成绩的百分比不能超过100%！");
            }
            //判断freexs中是否已存在数据
            VeJwCjFreeXs freexs = veJwCjFreeXsService.getByFreeid(veJwCjFree.getId());
            if (freexs == null) {
                //fx.setFreeid(veJwCjFree.getId());
                //veJwCjFreeXsService.save(fx);
                freexs = new VeJwCjFreeXs();
                freexs.setFreeid(veJwCjFree.getId());
            }
            freexs.setRatio(fx.getRatio());
            freexs.setScore(fx.getScore());
            freexs.setCjlxid(fx.getCjlxid());
            freexs.setFinalscore(new BigDecimal(0));

            veJwCjFreeXsService.saveOrUpdate(freexs);
        }
        if (veJwCjFree.getReasontidText() != null) {
            veJwCjFree.setReasontid(JwTextUtils.addText(veJwCjFree.getReasontidText()));
        }

        VeJwCjFree old = veJwCjFreeService.getById(veJwCjFree.getId());
        if (old.getStuid() != veJwCjFree.getStuid()) {
            /*try {
                Result<JSONObject> result = commonApi.getStudentById(CommonApi.COMMON_TOKEN_KEY, veJwCjFree.getStuid());
                JSONObject student = result.getResult();
                if (student == null) {
                    return Result.error("学生信息错误！");
                }
                veJwCjFree.setXm(student.getString("xm"));
                veJwCjFree.setXh(student.getString("xh"));
            } catch (Exception e) {
                return Result.error("学生信息错误%！");
            }*/
            VeBaseStudent student = veBaseStudentService.getById(veJwCjFree.getStuid());
            if (student != null) {
                veJwCjFree.setXm(student.getXm());
                veJwCjFree.setXh(student.getXh());
            }
            //根据班级id找班级信息
            VeBaseBanji veBaseBanji = veBaseBanjiService.findById(veJwCjFree.getJxbid());
            if (veBaseBanji != null) {
                veJwCjFree.setGradeid(veBaseBanji.getGradeId());
            }
        }
        veJwCjFreeService.updateById(veJwCjFree);
        return Result.ok("编辑成功!");
    }

    /**
     * 审核
     *
     * @param veJwCjFree
     * @return
     */
    @AutoLog(value = "免缓缺成绩登记-审核")
    @ApiOperation(value = "免缓缺成绩登记-审核", notes = "免缓缺成绩登记-审核")
    @PutMapping(value = "/audit")
    public Result<?> audit(@RequestBody VeJwCjFree veJwCjFree) {
        VeJwCjFree old = veJwCjFreeService.getById(veJwCjFree.getId());
        if (old == null) {
            return Result.error("记录不存在!");
        }
        if (old.getAuditstatus() == ConfigConstant.AUDIT_AGREE) {
            return Result.error("记录已审核!");
        }
        VeJwCjFree data = new VeJwCjFree();
        data.setId(old.getId());
        if (veJwCjFree.getAudittidText() != null) {
            data.setAudittid(JwTextUtils.addText(veJwCjFree.getAudittidText()));
        }
        data.setAuditstatus(veJwCjFree.getAuditstatus());
        veJwCjFreeService.updateById(data);
        return Result.ok("处理成功!");
    }


    /**
     * 批量通过
     *
     * @param jsonObject
     * @return
     */
    @AutoLog(value = "成绩类型-通过")
    @ApiOperation(value = "成绩类型-通过", notes = "成绩类型-通过")
    @PutMapping(value = "/stateBatch")
    public Result<?> stateBatch(@RequestBody JSONObject jsonObject) {
        if (!jsonObject.containsKey("ids")) {
            return Result.error("参数错误!");
        }
        String ids = jsonObject.getString("ids");
        VeJwCjFree data = new VeJwCjFree();
        data.setAuditstatus(ConfigConstant.AUDIT_AGREE);
        LambdaQueryWrapper<VeJwCjFree> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(VeJwCjFree::getId, Arrays.asList(ids.split(",")));
        veJwCjFreeService.update(data, queryWrapper);
        return Result.ok("通过成功");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "免缓缺成绩登记-通过id删除")
    @ApiOperation(value = "免缓缺成绩登记-通过id删除", notes = "免缓缺成绩登记-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        veJwCjFreeService.removeById(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "免缓缺成绩登记-批量删除")
    @ApiOperation(value = "免缓缺成绩登记-批量删除", notes = "免缓缺成绩登记-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.veJwCjFreeService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "免缓缺成绩登记-通过id查询")
    @ApiOperation(value = "免缓缺成绩登记-通过id查询", notes = "免缓缺成绩登记-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        VeJwCjFree veJwCjFree = veJwCjFreeService.getById(id);
        if (veJwCjFree == null) {
            return Result.error("未找到对应数据");
        }
        return Result.ok(veJwCjFree);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param veJwCjFree
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, VeJwCjFree veJwCjFree) {
        return super.exportXls(request, veJwCjFree, VeJwCjFree.class, "免缓缺成绩登记");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, VeJwCjFree.class);
    }

}
